import { login, getUserInfo, loginOut } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/tokenOperate'

const state = {
  token: getToken(),
  name: '',
  roles: []
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        commit('SET_TOKEN', res.token)
        setToken(res.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  loginOut({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginOut().then(res => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        if (res.data) {
          if (res.data.loginName === 'admin') {
            res.data.roleIdList = ['all']
          }
          if (res.data.roleIdList && res.data.roleIdList.length > 0) {
            commit('SET_ROLES', res.data.roleIdList)
            commit('SET_NAME', res.data.userName)
            resolve()
          } else {
            commit('SET_TOKEN', '')
            reject('该用户没有角色信息！！！')
          }
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

